package com.fmdj.mis.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fmdj.common.util.CommonResult;
import com.fmdj.common.util.PageUtils;
import com.fmdj.mis.api.controller.form.*;
import com.fmdj.mis.api.db.pojo.RoleEntity;
import com.fmdj.mis.api.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/role")
@Tag(name = "RoleController", description = "角色Web接口")
@Slf4j
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("/selectRoleByPage")
    @Operation(summary = "查询角色分页数据")
    @SaCheckPermission(value = {"ROOT", "ROLE:SELECT"}, mode = SaMode.OR)
    public CommonResult selectRoleByPage(@RequestBody @Valid SearchRoleByPageForm form) {
        HashMap map = BeanUtil.toBean(form, HashMap.class);
        PageUtils pageUtils = roleService.searchRoleByPage(map);
        return CommonResult.ok().put(CommonResult.RETURN_PAGE, pageUtils);
    }

    @GetMapping("/selectAllRole")
    @Operation(summary = "查询所有角色数据")
    @SaCheckPermission(value = {"ROOT", "ROLE:SELECT"}, mode = SaMode.OR)
    public CommonResult selectAllRole() {
        ArrayList<HashMap> list = roleService.searchAllRole();
        return CommonResult.ok().put("list", list);
    }

    @PostMapping("/selectById")
    @Operation(summary = "根据id查询角色信息")
    @SaCheckPermission(value = {"ROOT", "ROLE:SELECT"}, mode = SaMode.OR)
    public CommonResult selectById(@RequestBody @Valid SearchRoleByIdForm form) {
        HashMap map = roleService.searchById(form.getId());
        return CommonResult.ok(map);
    }

    @PostMapping("/insert")
    @Operation(summary = "添加角色")
    @SaCheckPermission(value = {"ROOT", "ROLE:INSERT"}, mode = SaMode.OR)
    public CommonResult insert(@Valid @RequestBody InsertRoleForm form) {
        RoleEntity roleEntity = new RoleEntity();

        roleEntity.setRoleName(form.getRoleName());
        roleEntity.setDesc(form.getDesc());
        //将权限数组转成json字符串
        JSONArray jsonArray = JSONUtil.parseArray(form.getPermissions());
        roleEntity.setPermissions(jsonArray.toString());

        int rows = roleService.insertRole(roleEntity);

        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/update")
    @Operation(summary = "修改角色")
    @SaCheckPermission(value = {"ROOT", "ROLE:UPDATE"}, mode = SaMode.OR)
    public CommonResult update(@Valid @RequestBody UpdateRoleForm form) {
        RoleEntity roleEntity = new RoleEntity();

        roleEntity.setRoleName(form.getRoleName());
        roleEntity.setDesc(form.getDesc());
        //将权限数组转成json字符串
        JSONArray jsonArray = JSONUtil.parseArray(form.getPermissions());
        roleEntity.setPermissions(jsonArray.toString());
        roleEntity.setId(form.getId());

        int rows = roleService.updateRole(roleEntity);
        //如果用户修改成功，并且用户修改了该角色的关联权限
        if (rows == 1 && form.getChanged()) {
            //把该角色关联的用户踢下线
            ArrayList<Integer> list = roleService.searchUserIdByRoleId(form.getId());
            list.forEach(userId -> {
                StpUtil.logoutByLoginId(userId);
            });
        }
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/deleteRoleByIds")
    @Operation(summary = "删除角色")
    @SaCheckPermission(value = {"ROOT", "ROLE:DELETE"}, mode = SaMode.OR)
    public CommonResult deleteRoleByIds(@Valid @RequestBody DeleteRoleByIdsForm form) {
        int row = roleService.deleteRoleByIds(form.getIds());
        return CommonResult.ok().put(CommonResult.RETURN_ROW, row);
    }
}
